<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);

require_once "./lib/WxPay.Api.php";
require_once './lib/WxPay.Notify.php';
require_once './lib/log.php';

//初始化日志

$logHandler= new CLogFileHandler(APPPATH."logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
    protected $CI;
    public function __construct() {
        //parent::__construct();
        $this->CI =&get_instance();
        $this->CI->load->helper('url');
        $this->CI->load->database();
    }

	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
    {
        //{"appid":"wxb015f10e8910a848","attach":"test","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1226831302","nonce_str":"0oiy6w85p8xljrav29pg8t5o8g068286","openid":"o-_zhsmFPZnH5FIXhMdWJZuwJNAA","out_trade_no":"122683130220150701095830","result_code":"SUCCESS","return_code":"SUCCESS","sign":"1DDA993228F935690087F804B0122E2C","time_end":"20150701095854","total_fee":"1","trade_type":"JSAPI","transaction_id":"1008051017201507010329604448"}
        $logMsg = json_encode($data);
		Log::DEBUG("call back:" .$logMsg) ;
		$notfiyOutput = array();
        //$attachArray = base64_decode($data['attach']);
        if($data['result_code']==='SUCCESS') {
            $this->CI->db->update('t_payrecord',array(
                'status'=>2,
                'transid'=>$data['transaction_id'],
            ),array('outtransno'=>$data['out_trade_no']));
            Log::DEBUG("sql update:" .$this->CI->db->last_query()) ;
        }
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		return true;
	}
}

